package com.youxuit.youxu.kecheng.CASandAtomic;

import lombok.SneakyThrows;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class PrintABCByLock {
    private static int state = 0;

    private static ReentrantLock lock = new ReentrantLock();

    private static Condition conditionA = lock.newCondition();

    private static Condition conditionB = lock.newCondition();

    private static Condition conditionC = lock.newCondition();

    public static void main(String[] args) {

        Thread threadA = new Thread(() -> printContext(0, "A", conditionA, conditionB));
        Thread threadB = new Thread(() -> printContext(1, "B", conditionB, conditionC));
        Thread threadC = new Thread(() -> printContext(2, "C", conditionC, conditionA));
        threadA.start();
        threadB.start();
        threadC.start();
    }

    @SneakyThrows
    private static void printContext(int flag, String context, Condition curCondition, Condition nextCondition) {
        for (int i = 0; i < 100; i++) {
            lock.lock();

            try {
                while (state % 3 == flag) {
                    System.out.printf("\n第%s次输入,输出%s", i, context);
                    state++;
                }
                nextCondition.signal();
                curCondition.await();
            } finally {
                lock.unlock();
            }

        }
    }

}
